﻿using System.Collections.Concurrent;
using System.Net.WebSockets;
using System.Text;

namespace DongFangGuoKai.WCSPlatform.WebApi.Utils.WebSocketCommon
{
    /// <summary>
    /// WebSocketConnectManager 类用于管理所有 WebSocket 连接
    /// </summary>
    public class WebSocketConnectManager
    {
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="logger"></param>
        public WebSocketConnectManager(ILogger<WebSocketConnectManager> logger)
        {
            this.logger = logger;
        }
        private ConcurrentDictionary<string, WebSocket> _sockets = new ConcurrentDictionary<string, WebSocket>();
        private readonly ILogger<WebSocketConnectManager> logger;

        /// <summary>
        /// 添加新的 WebSocket 连接
        /// </summary>
        /// <param name="id"></param>
        /// <param name="socket"></param>
        public void AddSocket(string id, WebSocket socket)
        {
            _sockets.TryAdd(id, socket);
            logger.LogInformation($"ip地址为[{id}]的客户端连接WebSocket成功");
        }

        /// <summary>
        /// 根据id移除 WebSocket 连接
        /// </summary>
        /// <param name="id"></param>
        public void RemoveSocket(string id)
        {
            _sockets.TryRemove(id, out _);
            logger.LogInformation($"移除ip地址{id}的WebSocket的连接");
        }

        /// <summary>
        /// 根据id获取 WebSocket 连接
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public WebSocket? GetSocketById(string id)
        {
            if (_sockets.TryGetValue(id, out WebSocket socket)) return socket;
            return null;
        }


        /// <summary>
        /// 获取所有 WebSocket 连接
        /// </summary>
        /// <returns></returns>
        private ConcurrentDictionary<string, WebSocket> GetAllSockets() => _sockets;

        private async Task SendMessage(WebSocket socket, string message)
        {
            try
            {
                var buffer = Encoding.UTF8.GetBytes(message);
                await socket.SendAsync(new ArraySegment<byte>(buffer, 0, buffer.Length), WebSocketMessageType.Text, true, CancellationToken.None);
                logger.LogInformation($"推送消息:{message}");
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        /// <summary>
        /// 示例：向所有客户端发送消息
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task SendMessageToAllClients(string message)
        {
            var sockets = GetAllSockets();
            foreach (var socket in sockets.Values)
            {
                try
                {
                    await SendMessage(socket, message);
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }

        /// <summary>
        /// 发送消息给特定客户端
        /// </summary>
        /// <param name="clientId">客户id</param>
        /// <param name="message">发送的消息</param>
        /// <returns></returns>
        public async Task SendMessageToClient(string clientId, string message)
        {
            var socket = GetSocketById(clientId);
            if (socket != null)
            {
                try
                {
                    await SendMessage(socket, message);
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }

    }

}
